package com.situ.mall.web.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.situ.mall.common.entity.Member;
import com.situ.mall.common.service.IMemberService;

import com.situ.mall.common.util.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;


import javax.servlet.http.Cookie;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/")
public class LoginController {

    @Autowired
    private IMemberService memberService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/login")
    public String page() {
        return "login";
    }


    @PostMapping("/login")
    public String login(String username, String password, Model model) {

        Member m = memberService.login(username, password);
        if (m == null) {
            model.addAttribute("errMsg", "该账号不存在");
            return "login";
        } else if (m.getStatus().equals("2")) {
            model.addAttribute("errMsg", "该账号已被锁定，无法登录");
            return "login";
        }
        Object o = redisTemplate.opsForValue().get("err-" + username);
        if (o != null) {
            int i = (int) o;
            if (i == 4) {
                //给前台返回一个失败原因
                model.addAttribute("errMsg", "连续失败5次,锁定1分钟,1分钟后在试");
                return "login";
            }
        }

        if (m.getStatus().equals("1") && m.getPassword().equals(password)) {
            //登陆成功把之前保存的失败次数删掉
            redisTemplate.delete("err-" + username);
            RequestUtil.setCurrent(m);
            return "redirect:/";
        } else {//用户名密码输入错误
            //在redis中记录 username 这个用户失败了
            //先判断之前有没有存过
            if (o != null) {
                redisTemplate.opsForValue().set("err-" + username, (int) o + 1, 1, TimeUnit.MINUTES);
            } else {
                redisTemplate.opsForValue().set("err-" + username, 1, 1, TimeUnit.MINUTES);
                model.addAttribute("errMsg", "用户名密码错误，连续失败5次，账号锁定，您还有" + 4 + "次机会");
            }
            ;
            if (o != null) {
                int oo = 4 - (int) o;
                model.addAttribute("errMsg", "用户名密码错误，连续失败5次，账号锁定，您还有" + oo + "次机会");
            }
            return "login";
        }

    }

}
